package com.tianji.chat.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.chat.domain.po.Task;
import com.tianji.chat.domain.vo.TaskVO;
import com.tianji.chat.storage.IFileStorage;
import com.tianji.chat.domain.dto.FileDTO;
import com.tianji.chat.domain.po.File;
import com.tianji.chat.enums.FileErrorInfo;
import com.tianji.chat.enums.FileStatus;
import com.tianji.chat.mapper.FileMapper;
import com.tianji.chat.service.IFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.CommonException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author pku-hlp
 * @since 2024-01-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {


    private final IFileStorage fileStorage;


    @Override
    public FileDTO uploadFile(MultipartFile file) {
        // 1.获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2.生成新文件名
        String filename = generateNewFileName(originalFilename);
        // 3.上传文件
        String requestId = fileStorage.uploadFile(file);
        if (requestId.equals("-1")){
            throw new RuntimeException("上传失败");
        }
        // 4.写入数据库
        File fileInfo = null;
        try {
            fileInfo = new File();
            fileInfo.setFilename(originalFilename);
            fileInfo.setKey(filename);
            fileInfo.setStatus(FileStatus.UPLOADED);
            fileInfo.setRequestId(requestId);
//            fileInfo.setPlatform(properties.getFile());
            save(fileInfo);
        } catch (Exception e) {
            log.error("文件信息保存异常", e);
//            fileStorage.deleteFile(filename);
            throw new DbException(FileErrorInfo.Msg.FILE_UPLOAD_ERROR);
        }
        log.info(requestId);
        // 5.返回
        FileDTO fileDTO = new FileDTO();
        fileDTO.setId(fileInfo.getId());
        fileDTO.setPath(requestId);
        fileDTO.setFilename(originalFilename);
        return fileDTO;
    }

    @Override
    public FileDTO getFileInfo(Long id) {
        File file = getById(id);
        if (file == null) {
            return null;
        }
        return FileDTO.of(file.getId(), file.getFilename(), file.getRequestId());
    }

    @Override
    public PageDTO<FileDTO> queryFilePage(PageQuery query) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.分页查询
        // select * from file where user_id = #{userId} order by update_time limit 0, 5
        Page<File> page = lambdaQuery()
                .eq(File::getDepId, userId) // where dep_id = #{userId}
                .page(query.toMpPage("update_time", false));
        List<File> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }

        // 3.封装VO返回
        List<FileDTO> list = new ArrayList<>(records.size());
        // 4.1.循环遍历，把Task转为VO
        for (File r : records) {
            // 4.2.拷贝基础属性到vo
            FileDTO vo = BeanUtils.copyBean(r, FileDTO.class);
            list.add(vo);
        }
        return PageDTO.of(page, list);
    }

    private String generateNewFileName(String originalFilename) {
        // 1.获取后缀
        String suffix = StringUtils.subAfter(originalFilename, ".", true);
        // 2.生成新文件名
        return UUID.randomUUID().toString(true) + "." + suffix;
    }

}
